﻿using WRJClient.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WRJClient.DAL
{
    public class RestResult
    {
        public string statusCode;
        public object data;
        public string desc;
    }

    public class Api
    {
        private static string _token = "";

        public static string Token
        {
            get { return _token; }
        }

        public class ApiResponse
        {
            public string statusCode { get; set; }
            public object data { get; set; }
            public string desc { get; set; }
        }

        private static ApiResponse Post(string url, string argsjson = null)
        {
            try
            {
                var request = new RestRequest(url, Method.POST);
                if (!string.IsNullOrEmpty(argsjson))
                {
                    request.AddParameter("application/json; charset=utf-8", argsjson, ParameterType.RequestBody);
                    request.RequestFormat = RestSharp.DataFormat.Json;
                }
                RestClient _client = new RestClient(string.Format("http://{0}:{1}", Properties.Settings.Default.ServerIp,
                Properties.Settings.Default.ServerPort));

                IRestResponse response = _client.Execute(request);
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    return JsonConvert.DeserializeObject<ApiResponse>(response.Content);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            return null;
        }

        public static bool Auth(string username, string password)
        {
            _token = "";
            string json = string.Format("{{\"username\":\"{0}\",\"password\":\"{1}\"}}", username, password);
            ApiResponse response = Post("/api/auth", json);

            if (response != null && response.statusCode == "0")
            {
                _token = response.data as string;
                return true;
            }
            return false;
        }

        public static List<UAVModel> GetAllUAV()
        {
            List<UAVModel> list = new List<UAVModel>();
            string json = string.Format("{{\"token\":\"{0}\"}}", _token);
            ApiResponse response = Post("/api/uav/query", json);
            if (response != null && response.statusCode == "0")
            {
                try
                {
                    JObject jobj = JObject.Parse(response.data.ToString());
                    JArray jarray = jobj.GetValue("content") as JArray;

                    foreach (var item in jarray)
                    {

                        UAVModel model = new UAVModel
                        {
                            DbId = item["dbId"].ToString(),
                            UavId = item["uavId"].ToString(),
                            Manufacturer = item["manufacturer"].ToString(),
                            Type = item["type"].ToString(),
                            MaxSpeed = !string.IsNullOrEmpty(item["maxSpeed"].ToString()) ? (int)item["maxSpeed"] : 0,
                            Ceiling = !string.IsNullOrEmpty(item["ceiling"].ToString()) ? (int)item["ceiling"] : 0,
                            Voyage = !string.IsNullOrEmpty(item["voyage"].ToString()) ? (int)item["voyage"] : 0,
                            CreateTime = item["createTime"].ToString(),
                            CheckTime = item["checkTime"].ToString(),
                            Image = item["image"].ToString(),
                            WorkStationId = item["orgid"].ToString(),
                        };
                        list.Add(model);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            }
            return list;
        }

        public static List<WorkStationModel> GetAllControlCenter()
        {
            List<WorkStationModel> list = new List<WorkStationModel>();

            string json = string.Format("{{\"token\":\"{0}\",\"type\":2}}", _token);
            ApiResponse response = Post("/api/workstation/query", json);
            if (response != null && response.statusCode == "0")
            {
                try
                {
                    JObject jobj = JObject.Parse(response.data.ToString());
                    JArray jarray = jobj.GetValue("content") as JArray;

                    foreach (var item in jarray)
                    {
                        WorkStationModel model = new WorkStationModel
                        {
                            DbId = item["dbId"].ToString(),
                            WorkStationId = item["workstationId"].ToString(),
                            Name = item["name"].ToString(),
                            Type = !string.IsNullOrEmpty(item["type"].ToString()) ? (int)item["type"] : 0,
                            //Staffs = item["staffs"].ToString(),
                            Tel = item["tel"].ToString(),
                            Desc = item["desc"].ToString(),
                            Longitude = !string.IsNullOrEmpty(item["longitude"].ToString()) ? (double)item["longitude"] : 0,
                            Latitude = !string.IsNullOrEmpty(item["latitude"].ToString()) ? (int)item["latitude"] : 0,
                            Ip = item["ip"].ToString(),
                            Radius = 10
                        };
                        JArray jstaffs = JArray.Parse(item["staffs"].ToString());
                        foreach (var jstaff in jstaffs)
                        {
                            StaffModel staff = new StaffModel
                            {
                                DbId = jstaff["dbId"].ToString(),
                                Name = jstaff["name"].ToString(),
                                Title = jstaff["title"].ToString(),
                                Tel = jstaff["tel"].ToString(),
                                Image = jstaff["image"].ToString(),
                                Age = !string.IsNullOrEmpty(jstaff["age"].ToString()) ? (int)jstaff["age"] : 0,
                                Gender = !string.IsNullOrEmpty(jstaff["gender"].ToString()) ? (int)jstaff["gender"] : 0
                            };
                            model.Staffs.Add(staff);
                        }

                        list.Add(model);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            }
            return list;
        }
        public static List<WorkStationModel> GetAllWorkStation()
        {
            List<WorkStationModel> list = new List<WorkStationModel>();

            string json = string.Format("{{\"token\":\"{0}\",\"type\":1}}", _token);
            ApiResponse response = Post("/api/workstation/query", json);
            if (response != null && response.statusCode == "0")
            {
                try
                {
                    JObject jobj = JObject.Parse(response.data.ToString());
                    JArray jarray = jobj.GetValue("content") as JArray;

                    foreach (var item in jarray)
                    {
                        WorkStationModel model = new WorkStationModel
                        {
                            DbId = item["dbId"].ToString(),
                            WorkStationId = item["workstationId"].ToString(),
                            Name = item["name"].ToString(),
                            Type = !string.IsNullOrEmpty(item["type"].ToString()) ? (int)item["type"] : 0,
                            //Staffs = item["staffs"].ToString(),
                            Tel = item["tel"].ToString(),
                            Desc = item["desc"].ToString(),
                            Longitude = !string.IsNullOrEmpty(item["longitude"].ToString()) ? (double)item["longitude"] : 0,
                            Latitude = !string.IsNullOrEmpty(item["latitude"].ToString()) ? (double)item["latitude"] : 0,
                            Ip = item["ip"].ToString(),
                            Radius = 10
                        };
                        JArray jstaffs = JArray.Parse(item["staffs"].ToString());
                        foreach (var jstaff in jstaffs)
                        {
                            StaffModel staff = new StaffModel
                            {
                                DbId = jstaff["dbId"].ToString(),
                                Name = jstaff["name"].ToString(),
                                Title = jstaff["title"].ToString(),
                                Tel = jstaff["tel"].ToString(),
                                Image = jstaff["image"].ToString(),
                                Age = !string.IsNullOrEmpty(jstaff["age"].ToString()) ? (int)jstaff["age"] : 0,
                                Gender = !string.IsNullOrEmpty(jstaff["gender"].ToString()) ? (int)jstaff["gender"] : 0
                            };
                            model.Staffs.Add(staff);
                        }

                        list.Add(model);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            }
            return list;
        }

        public static List<MissionModel> GetAllMission()
        {
            List<MissionModel> list = new List<MissionModel>();

            string json = string.Format("{{\"token\":\"{0}\"}}", _token);
            ApiResponse response = Post("/api/mission/query", json);
            if (response != null && response.statusCode == "0")
            {
                try
                {
                    JObject jobj = JObject.Parse(response.data.ToString());
                    JArray jarray = jobj.GetValue("content") as JArray;

                    foreach (var item in jarray)
                    {
                        MissionModel model = new MissionModel
                        {
                            DbId = item["dbId"].ToString(),
                            Name = item["name"].ToString(),
                            CreateTime = item["createTime"].ToString(),
                            SendTime = item["sendTime"].ToString(),
                            StartTime = item["startTime"].ToString(),
                            EndTime = item["endTime"].ToString(),
                            UavId = item["uavId"].ToString(),
                            WorkStationId = item["workstationId"].ToString(),
                            Type = !string.IsNullOrEmpty(item["type"].ToString()) ? (int)item["type"] : 0,
                            Details = item["details"].ToString(),
                            AirlineId = item["airlineId"].ToString(),
                            Report = item["report"].ToString(),
                            State = !string.IsNullOrEmpty(item["state"].ToString()) ? (int)item["state"] : 0
                        };
                        list.Add(model);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            }
            return list;
        }

        public static List<InfomationModel> GetAllInfomation()
        {
            List<InfomationModel> list = new List<InfomationModel>();

            string json = string.Format("{{\"token\":\"{0}\"}}", _token);
            ApiResponse response = Post("/api/information/query", json);
            if (response != null && response.statusCode == "0")
            {
                try
                {
                    JObject jobj = JObject.Parse(response.data.ToString());
                    JArray jarray = jobj.GetValue("content") as JArray;

                    foreach (var item in jarray)
                    {
                        InfomationModel model = new InfomationModel
                        {
                            Name = item["name"].ToString(),
                            DbId = item["dbId"].ToString(),
                            MissionId = item["missionId"].ToString(),
                            Time = item["time"].ToString(),
                            Type = !string.IsNullOrEmpty(item["type"].ToString()) ? (int)item["type"] : 0,
                            Priority = !string.IsNullOrEmpty(item["priority"].ToString()) ? (int)item["priority"] : 0,
                            Position = item["position"].ToString(),
                            Desc = item["desc"].ToString()
                        };
                        list.Add(model);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            }
            return list;
        }

        public static List<AirlineModel> GetAllAirline()
        {
            List<AirlineModel> list = new List<AirlineModel>();

            string json = string.Format("{{\"token\":\"{0}\"}}", _token);
            ApiResponse response = Post("/api/airline/query", json);
            if (response != null && response.statusCode == "0")
            {
                try
                {
                    JObject jobj = JObject.Parse(response.data.ToString());
                    JArray jarray = jobj.GetValue("content") as JArray;

                    foreach (var item in jarray)
                    {
                        AirlineModel model = new AirlineModel
                        {
                            DbId = item["dbId"].ToString(),
                            Name = item["name"].ToString(),
                            Waypoints = item["waypoints"].ToString(),
                            CreateTime = item["createTime"].ToString(),
                            Desc = item["desc"].ToString()
                        };
                        list.Add(model);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            }
            return list;
        }

        public static List<ZoneModel> GetAllZone()
        {
            List<ZoneModel> list = new List<ZoneModel>();

            string json = string.Format("{{\"token\":\"{0}\"}}", _token);
            ApiResponse response = Post("/api/zone/query", json);
            if (response != null && response.statusCode == "0")
            {
                try
                {
                    JObject jobj = JObject.Parse(response.data.ToString());
                    JArray jarray = jobj.GetValue("content") as JArray;

                    foreach (var item in jarray)
                    {
                        ZoneModel model = new ZoneModel
                        {
                            DbId = item["dbId"].ToString(),
                            Name = item["name"].ToString(),
                            Type = !string.IsNullOrEmpty(item["type"].ToString()) ? (int)item["type"] : 0,
                            Shape = !string.IsNullOrEmpty(item["shape"].ToString()) ? (int)item["shape"] : 0,
                            Data = item["data"].ToString(),
                            Desc = item["desc"].ToString(),
                            StartTime = item["startTime"].ToString(),
                            EndTime = item["endTime"].ToString()
                        };
                        list.Add(model);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            }
            return list;
        }
    }
}
